package com.zhenmaitang.clinic_sys.service.impl;

import com.zhenmaitang.clinic_sys.entity.UserRole;
import com.zhenmaitang.clinic_sys.mapper.UserRoleMapper;
import com.zhenmaitang.clinic_sys.service.RoleService;
import com.zhenmaitang.clinic_sys.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserRoleServiceImpl implements UserRoleService {
    
    @Autowired
    private UserRoleMapper userRoleMapper;
    
    @Autowired
    private RoleService roleService;

    @Override
    public List<UserRole> getUserRolesByUserId(Integer userId) {
        return userRoleMapper.findByUserId(userId);
    }

    @Override
    public UserRole createUserRole(UserRole userRole) {
        userRoleMapper.insert(userRole);
        return userRole;
    }

    @Override
    public void deleteUserRole(Integer userId, Integer roleId) {
        userRoleMapper.deleteByUserIdAndRoleId(userId, roleId);
    }

    @Override
    public void deleteByUserId(Integer userId) {
        userRoleMapper.deleteByUserId(userId);
    }

    @Override
    public boolean hasRole(Integer userId, String roleName) {
        // 根据角色名称查找角色ID，然后检查用户是否有该角色
        try {
            Integer roleId = roleService.getRoleByName(roleName).getId();
            return userRoleMapper.existsByUserIdAndRoleId(userId, roleId);
        } catch (Exception e) {
            // 角色不存在或查询失败
            return false;
        }
    }
}